class MyPromise {
  constructor(executor){
    this.value = undefined;
    this.reason = undefined;
    this.state = 'pending';
    this.onResolvedCallbacks = [];
    this.onRejectedCallbacks = [];
    let resolve = value =>{
      if(this.state==='pending'){
        this.state = 'fulfilled';
        this.value = value;
        this.onResolvedCallbacks.forEach(fn=>fn());
      }
    };
    let reject = reason =>{
      if(this.state==='pending'){
        this.state = 'rejected';
        this.reason = reason;
        this.onRejectedCallbacks.forEach(fn => fn());
      }
    };
    try{
      executor(resolve,reject);
    }catch(e){
      reject(e);
    }
  };
  then(onFulfilled,onRejected){
    // onFulfilled如果不是函数，就忽略onFulfilled，直接返回value
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    // onRejected如果不是函数，就忽略onRejected，直接扔出错误
    onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err };
    let promise = new MyPromise((resolve,reject)=>{
      if(this.state==='pending'){
        this.onResolvedCallbacks.push(()=>{
          // onFulfilled(this.value);
          let x = onFulfilled(this.value);
          resolvePromise(promise, x, resolve, reject);
          });
        this.onRejectedCallbacks.push(() =>{
          // onRejected(this.reason);
          let x = onRejected(this.reason);
          resolvePromise(promise, x, resolve, reject);
          });
      }
      if(this.state==='fulfilled'){
        // onFulfilled(this.value);
        let x = onFulfilled(this.value);
        resolvePromise(promise, x, resolve, reject);
      }
      if (this.state ==='rejected'){
        // onRejected(this.reason);
        let x = onRejected(this.reason);
        resolvePromise(promise, x, resolve, reject);
      }
    })
    return promise
  }
};
function resolvePromise(promise,x,resolve,reject){
  // 循环引用报错
  if(x===promise){
    return reject(new TypeError('chaining cycle detected for promise'));
  };
  //防止多次调用
  let called;
  //x不是null 且x是对象或者函数
  if(x!=null&&(typeof x==='object'||typeof x ==='function')){
    try{
      // A+规定。声明then=x的then方法
      let then = x.then;
      //如果让then是函数，就默认是promise了
      if(typeof then ==='function'){
        //就让then 执行 第一个参数是this 后面是成功的回调和失败的回调
        then.call(x,y=>{
          //成功和失败只能调用一个
          if(called) return;
          called = true;
          //resolve 的结果依旧是promise 那就继续解析
          resolvePromise(promise,y,resolve.reject); 
        },err=>{
            // 成功和失败只能调用一个
            if (called) return;
            called = true;
            reject(err);// 失败了就失败了
        })
      }else {
        resolve(x);
      }
    }catch(e){
      // 也属于失败
      if (called) return;
      called = true;
      // 取then出错了那就不要在继续执行了
      reject(e); 
    }
  }else {
    resolve(x);
  }
}
// export default MyPromise;
// module.exports = MyPromise;
// let p = new MyPromise((resolve,reject)=>{
//   console.log('mypromise');
//   setTimeout(function(){
//       resolve('resolve')
//   },0)
// });
// let p1=p.then(res=>{
//   console.log(res)
//   let p1 = new MyPromise(resolve => {
//     resolve('resolve')
//   })
//   return p1
// });
// p1.then(res=>{
//   console.log(res)
// })
// setTimeout(() => {
//   console.log('timer1')
//   Promise.resolve().then(function () {
//     console.log('promise1')
//   })
// }, 0)
// setTimeout(() => {
//   console.log('timer2')
//   Promise.resolve().then(function () {
//     console.log('promise2')
//   })
// }, 0)
Promise.resolve().then(() => {
  console.log('Promise1')
  setTimeout(() => {
    console.log('setTimeout2')
  }, 0)
})
setTimeout(() => {
  console.log('setTimeout1')
  Promise.resolve().then(() => {
    console.log('Promise2')
  })
}, 0)


